import java.util.LinkedList;
import java.util.Queue;

public class demo1 {
    int []dx={0,0,1,-1};
    int []dy={1,-1,0,0};
    boolean[][]ret;
    int m;
    int n;
    public int maxAreaOfIsland(int[][] grid) {
        m=grid.length;
        n=grid[0].length;
        ret=new boolean[m][n];
        int maxSum=0;
        for(int i=0;i<m;i++){
            for (int j = 0; j <n ; j++) {
                if(grid[i][j]==1&& !ret[i][j])
                maxSum=Math.max(maxSum,dfs(grid,i,j));
            }
        }
        return maxSum;
    }
    public int dfs(int [][]grid,int i,int j){
        Queue<int[]>queue=new LinkedList<>();
        queue.add(new int[]{i,j});
        int sum=0;
        while (!queue.isEmpty()){
            int[] arr = queue.poll();
            int a=arr[0];
            int b=arr[1];
            ret[a][b]=true;
            sum++;
            for(int k=0;k<4;k++){
                int x=a+dx[k];
                int y=b+dy[k];
                if(x>=0&&x<m&&y>=0&&y<n&& !ret[x][y]&&grid[x][y]==1){
                    ret[x][y]=true;
                    queue.add(new int[]{x,y});
                }
            }
        }
        return sum;
    }
}
